<?php
/**
 * 《下载》实现类
 *
 * @author 孙晓晔
 * @version $Id: Common.class.php 513 2009-11-11 07:31:44Z sunxy $
 */

class Download {

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';
	}

	function tt($ip) {
		require_once APP_LIB . 'IpAddr.class.php';
		
		$ipaddr = new IpAddr();
		if ($ipaddr->contains("192.168.0.0/22", $ip)) {
			return "sj";
		}
		
		if ($ipaddr->contains("192.168.16.0/22", $ip)) {
			return "ns";
		}
		
		return "";
	}
	
	function _url($ff) {
		global $cfg;
		
		$upload = $cfg['upload'];
		
		$tt = 'tt';
		$fmt = "%s/upload/%s/%s";
		$file = sprintf($fmt, $upload, $tt, $ff);
		if (file_exists($file)) {
			return sprintf($fmt, '', $tt, $ff);
		}
		
		$tt = Download::tt($_SERVER['REMOTE_ADDR']);
		$file = sprintf($fmt, $upload, $tt, $ff);
		if (file_exists($file)) {
			return sprintf($fmt, '', $tt, $ff);
		}
		
		if ($tt == 'ns') {
			$url = 'http://ns.tecmold.net';
		} else {
			$url = 'http://sj.tecmold.net';
		}

		return sprintf($fmt, $url, 'tt', $ff);
	}
	
	function ff($type, $date, $id, $filename) {
		$dd = date('Y/m/d', strtotime($date));
		$fmt = "%s/%s/%s/%s";
		
		return sprintf($fmt, $type, $dd, $id, $filename);		
	}

	/**
	 * 计算地址
	 *
	 * @param string $type
	 * @param string $date
	 * @param integer $id
	 * @param string $filename
	 * @return string
	 */
	function url($type, $date, $id, $filename) {
		$ff = Download::ff($type, $date, $id, $filename);

		return Download::_url($ff);
	}

	/**
	 * 计算目录
	 *
	 * @param string $type
	 * @param string $date
	 * @param integer $id
	 * @return string
	 */
	function dir($type, $date, $id) {
		global $cfg;
		
		$upload = $cfg['upload'];
		
		$dd = date('Y/m/d', strtotime($date));

		$fmt = "%s/upload/tt/%s/%s/%s/";
		$dir = sprintf($fmt, $upload, $type, $dd, $id);

		return $dir;
	}
	
	function dir2($type, $id) {
		global $cfg;
		
		$upload = $cfg['upload'];
		
		$fmt = "%s/upload/tt/%s/%s/";
		$dir = sprintf($fmt, $upload, $type, $id);

		return $dir;
	}
	
	function url2($type, $id, $filename) {
		$ff = Download::ff2($type, $id, $filename);
		if (empty($ff)) {
			return '';
		}

		return Download::_url2($ff);
	}
	
	function ff2($type, $id, $filename) {
		if (empty($filename)) {
			return '';
		}
		
		$fmt = "%s/%s/%s";
		
		return sprintf($fmt, $type, $id, $filename);		
	}
	
	function _url2($ff) {
		global $cfg;
		
		$upload = $cfg['upload'];
		
		$tt = 'tt';
		$fmt = "%s/upload/%s/%s";
		$file = sprintf($fmt, $upload, $tt, $ff);
		
		if (file_exists($file)) {
			return sprintf($fmt, '', $tt, $ff);
		}
		
		if (empty($ff)) {
			return '';
		}
		
		return sprintf($fmt, 'http://sj.tecmold.net', 'tt', $ff);
	}
}